package net.hanjava.roas;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;

/**
 * Represents in-memory model for existing resource bundle. bundle has multiple
 * <code>LocaleTranslation</code>s for each locale.
 * 
 * @author behumble@hanjava.net
 */
public class TextBundleModel {
	private String basename;
	private Locale defaultLocale = new Locale("en");
	private List<Translation> translations;

	public TextBundleModel(String basename) {
		if (basename == null)
			throw new IllegalArgumentException("basename can not be null");
		this.basename = basename;
		translations = new ArrayList<Translation>();
	}

	public void addTranslation(Translation tranlation) {
		translations.add(tranlation);
	}

	public Iterator<Translation> getTranslations() {
		return translations.iterator();
	}

	public List<Locale> getLocales() {
		List<Locale> result = new ArrayList<Locale>();
		for (Iterator<Translation> it = getTranslations(); it.hasNext();) {
			Locale locale = it.next().getLocale();
			result.add(locale);
		}
		return result;
	}

	public String getName() {
		return basename;
	}

	@Override
	public String toString() {
		return String.format("[%s:%s]", basename, getLocales().toString());
	}

	public Translation getDefaultTranslation() {
		for(Iterator<Translation> it = getTranslations();it.hasNext();) {
			Translation t = it.next();
			if(t.getLocale().equals( getDefaultLocale() ) ) {
				return t;
			}
		}
		throw new IllegalStateException("Translation for default locale can not be found : "+getDefaultLocale());
	}

	public void setDefaultLocale(Locale locale) {
		this.defaultLocale = locale;
	}

	public Locale getDefaultLocale() {
		return defaultLocale;
	}
}